define([], function () {
    require.config({
    paths: {
        'ajcaptcha-verify': '../addons/ajcaptcha/js/verify',
        'crypto-js': '../addons/ajcaptcha/js/crypto-js'
    },
    shim: {
        'ajcaptcha-verify': {
            deps: [
                'jquery', 'crypto-js',
                'css!../addons/ajcaptcha/css/verify.css'
            ],
        }
    }
});

require(['form'], function (Form) {
    window.ajcaptcha = function (captcha) {
        require(['ajcaptcha-verify'], function (undefined) {
            captcha = captcha ? captcha : $("input[name=captcha]");
            if (captcha.length > 0) {
                var form = captcha.closest("form");
                var parentDom = captcha.parent();
                // 非文本验证码
                if ($("a[data-event][data-url]", parentDom).length > 0) {
                    return;
                }
                var container = captcha.closest("form");
                container = $("<div />").addClass("ajcaptcha-container");
                if (Config.ajcaptcha.captchaMode === 'fixed') {
                    container.css("margin-bottom", "15px");
                }
                if (captcha.parentsUntil(form, "div.form-group").length > 0) {
                    captcha.parentsUntil(form, "div.form-group").addClass("hidden");
                    container.insertAfter(captcha.parentsUntil(form, "div.form-group"));
                } else if (parentDom.is("div.input-group")) {
                    parentDom.addClass("hidden");
                    container.insertAfter(parentDom);
                } else {
                    container.appendTo(form);
                }
                var imgSizeWidth, imgSizeHeight;
                imgSizeWidth = Math.min(500, Math.max(310, container.width()));
                imgSizeHeight = imgSizeWidth / 2;

                captcha.attr("data-rule", "required");
                // 验证失败时进行操作
                captcha.on('invalid.field', function (e, result, me) {
                    //必须删除errors对象中的数据，否则会出现Layer的Tip
                    delete me.errors['captcha'];
                    if (!captcha.data("ajcaptcha")) {
                        render();
                    } else {
                        container.find(".mask").show();
                    }
                });

                var render = function () {
                    let baseUrl = Fast.api.fixurl("/addons/ajcaptcha");
                    let options = {
                        baseUrl: baseUrl,
                        mode: Config.ajcaptcha.captchaMode || 'pop',     //展示模式
                        containerId: 'use-undefined-id', //pop模式 必填 被点击之后出现行为验证码的元素id
                        imgSize: {       //图片的大小对象,有默认值{ width: '310px',height: '155px'},可省略
                            width: imgSizeWidth + 'px',
                            height: imgSizeHeight + 'px',
                        },
                        barSize: {          //下方滑块的大小对象,有默认值{ width: '310px',height: '50px'},可省略
                            width: imgSizeWidth + 'px',
                            height: '50px',
                        },
                        ready: function () {
                            if (!Config.ajcaptcha.preRender) {
                                form.find(".mask").show();
                            }
                        },  //加载完毕的回调
                        success: function (params) { //成功的回调
                            // params为返回的二次验证参数 需要在接下来的实现逻辑回传服务器
                            captcha.val(params.captchaVerification);
                            form.trigger("submit");
                        },
                        error: function () {
                        }        //失败的回调
                    };
                    let obj, captchaType = Config.ajcaptcha.captchaType;
                    if (captchaType === 'blockPuzzle') {
                        obj = container.slideVerify(options);
                    } else {
                        obj = container.pointsVerify(options);
                    }
                    captcha.data("ajcaptcha", obj);
                }

                // 预渲染
                if (Config.ajcaptcha.preRender) {
                    render();
                }

                // 监听表单错误事件
                form.on("error.form", function (e, data) {
                    captcha.val('');
                });
            }
        });
    };
    // ajcaptcha($("input[name=captcha]"));

    if (typeof Frontend !== 'undefined') {
        Frontend.api.preparecaptcha = function (btn, type, data) {
            require(['form'], function (Form) {
                $("#ajcaptchacontainer").remove();
                $("<div />").attr("id", "ajcaptchacontainer").addClass("hidden").html(Template("captchatpl", {})).appendTo("body");
                var form = $("#ajcaptchacontainer form");
                form.data("validator-options", {
                    valid: function (ret) {
                        data.captcha = $("input[name=captcha]", form).val();
                        Frontend.api.sendcaptcha(btn, type, data, function (data, ret) {
                            console.log("ok");
                        });
                        return true;
                    }
                })
                Form.api.bindevent(form);
            });
        };
    }

    var _bindevent = Form.events.bindevent;
    Form.events.bindevent = function (form) {
        _bindevent.apply(this, [form]);
        var captchaObj = $("input[name=captcha]", form);
        if (captchaObj.length > 0) {
            captchaObj.closest("form").find("button[type=submit]").removeAttr("disabled");
            ajcaptcha(captchaObj);
            if ($(form).attr("name") === 'captcha-form') {
                setTimeout(function () {
                    captchaObj.trigger("invalid.field", [{key: 'captcha'}, {errors: {}}]);
                }, 100);
            }
        }
    }
});

//判断系统深色模式变化，修改切换按钮
var matchMedia = window.matchMedia(('(prefers-color-scheme: dark)'));
matchMedia.addEventListener('change', function () {
    var mode = this.matches ? 'dark' : 'light';
    //只有当cookie中无手动定义值时才进行操作
    if (document.cookie.indexOf("thememode=") === -1 && Config.darktheme.mode === 'auto') {
        $("body").toggleClass("darktheme", mode === "dark");
    }
});

if (typeof Config.darktheme !== 'undefined' && Config.darktheme.switchbtn) {

    // 切换模式
    var switchMode = function (mode) {
        // 获取当前深色模式
        if (mode === 'auto') {
            var isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
            mode = isDarkMode ? 'dark' : 'light';
        }

        if (mode === 'auto') {
        } else if (mode === 'dark') {
            $("body").addClass("darktheme");
            $(".darktheme-link").removeAttr("media");
        } else {
            $("body").removeClass("darktheme");
            $(".darktheme-link").attr("media", "(prefers-color-scheme: dark)");
        }
    };

    // 创建Cookie
    var createCookie = function (name, value) {
        var date = new Date();
        date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
        var url = Config.moduleurl.replace(location.origin, "");
        var path = url ? url.substring(url.lastIndexOf("/")) : "/";
        document.cookie = encodeURIComponent(Config.cookie.prefix + name) + "=" + encodeURIComponent(value) + "; path=" + path + "; expires=" + date.toGMTString();
    };

    if (Config.controllername === 'index' && Config.actionname === 'index') {
        var mode = Config.darktheme.mode;
        if (mode === 'auto') {
            var isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
            mode = isDarkMode ? 'dark' : 'light';
        }
        var html = '<li class="theme-li">' +
            '<button type="button" title="切换' + (mode === 'dark' ? '浅色' : '深色') + '模式" data-mode="' + (mode === 'dark' ? 'light' : 'dark') + '" class="theme-toggle">' +
            '<svg class="sun-and-moon" aria-hidden="true" width="24" height="24" viewBox="0 0 24 24">\n' +
            '      <circle class="sun" cx="12" cy="12" r="6" mask="url(#moon-mask)" fill="currentColor" />\n' +
            '      <g class="sun-beams" stroke="currentColor">\n' +
            '        <line x1="12" y1="1" x2="12" y2="3" />\n' +
            '        <line x1="12" y1="21" x2="12" y2="23" />\n' +
            '        <line x1="4.22" y1="4.22" x2="5.64" y2="5.64" />\n' +
            '        <line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />\n' +
            '        <line x1="1" y1="12" x2="3" y2="12" />\n' +
            '        <line x1="21" y1="12" x2="23" y2="12" />\n' +
            '        <line x1="4.22" y1="19.78" x2="5.64" y2="18.36" />\n' +
            '        <line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />\n' +
            '      </g>\n' +
            '      <mask class="moon" id="moon-mask">\n' +
            '        <rect x="0" y="0" width="100%" height="100%" fill="white" />\n' +
            '        <circle cx="24" cy="10" r="6" fill="black" />\n' +
            '      </mask>\n' +
            '    </svg>' +
            '</button>' +
            '</li>';
        $(html).prependTo("#firstnav > div > ul");

        //点击切换按钮
        $(document).on("click", ".theme-toggle", function () {
            var mode = $(this).attr("data-mode");
            switchMode(mode);
            createCookie("thememode", mode);
            $("iframe").each(function () {
                try {
                    $(this)[0].contentWindow.$("body").trigger("swithmode", [mode]);
                } catch (e) {

                }
            });
            $(this).attr("data-mode", mode === 'dark' ? 'light' : 'dark').attr("title", '切换' + (mode === 'dark' ? '浅色' : '深色') + '模式');
        });

        //判断系统深色模式变化，修改切换按钮
        var matchMedia = window.matchMedia(('(prefers-color-scheme: dark)'));
        matchMedia.addEventListener('change', function () {
            var mode = this.matches ? 'dark' : 'light';
            //只有当cookie中无手动定义值时才切换
            if (document.cookie.indexOf("thememode=") === -1 && Config.darktheme.mode === 'auto') {
                $(".theme-toggle").attr("data-mode", mode === 'dark' ? 'light' : 'dark').attr("title", '切换' + (mode === 'dark' ? '浅色' : '深色') + '模式');
            }
        });
    } else {
        //添加事件
        $("body").on("swithmode", function (e, mode) {
            switchMode(mode);
            $("iframe").each(function () {
                try {
                    $(this)[0].contentWindow.$("body").trigger("swithmode", [mode]);
                } catch (e) {

                }
            });
        });
    }
}
});